package com.rankeiot.core.sqltoy;

import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.LFUCache;
import lombok.experimental.UtilityClass;
import org.sagacity.sqltoy.config.annotation.Column;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@UtilityClass
public class EnumColumnUtil {
    private static final Map<Enum, WeakReference<ColumnInfo>> FIELD_CACHE = new ConcurrentHashMap<>();

    private static final Cache<Enum,ColumnInfo> cache=new LFUCache<>(100);

    public static ColumnInfo getInfo(Enum column){
       return cache.get(column,()->getColumnInfo0(column));
//        return Optional.ofNullable(FIELD_CACHE.get(column))
//                .map(WeakReference::get)
//                .orElseGet(() -> {
//                    ColumnInfo v = getColumnInfo0(column);
//                    FIELD_CACHE.put(column, new WeakReference<>(v));
//                    return v;
//                });
    }
    private static  ColumnInfo getColumnInfo0(Enum column){
        Class domain = column.getDeclaringClass().getDeclaringClass();
        String field=column.name();
        String tableColumn = field;
        Column columnAnno = null;
        Field jfield = null;
        try {
            jfield = domain.getDeclaredField(field);
            columnAnno = jfield.getAnnotation(Column.class);
            tableColumn = columnAnno.name();

        } catch (NoSuchFieldException e)  {
            e.printStackTrace();
        }
        return new ColumnInfo(field, tableColumn, columnAnno);
    }

}
